// https://leetcode.cn/problems/can-place-flowers/
// Created by ade on 2022/8/10.
//
#include <iostream>
#include <vector>


using namespace std;

class Solution {
public:
    // 栈的方式效率很低
    bool canPlaceFlowers1(vector<int> &flowerbed, int n) {
        int len = flowerbed.size();
        if (len <= 2 && n > 0) {
            for (auto i : flowerbed) {
                if (i == 1) return false;
            }
            if (n <= 1) return true;
            return false;
        }

        int index = len - 1;
        int count = 0;
        while (index >= 0) {
            if (flowerbed[index] == 1) {
                count = 0;
            } else {
                count++;
                if (count == 3 || count == 2 && index == 0 || count == 2 && index == len - 2) {
                    n--;
                    count = 1;
                }
            }
            index--;
            cout << n << endl;

            if (n == 0) return true;
        }
        return false;
    }

    bool canPlaceFlowers(vector<int> &flowerbed, int n) {
        int len = flowerbed.size();
        if (len <= 2 && n >= 0) {
            for (auto i : flowerbed) {
                if(i == 1) n++;
            }
            return n < 2;
        }
        for (int i = 0; i < len; i++) {
            if (flowerbed[i] == 0) {
                if (i == 0 && flowerbed[1] == 0 ||
                    i == len - 1 && flowerbed[len - 2] == 0 ||
                    i >= 1 && i <= len - 2 && flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0
                        ) {
                    flowerbed[i] = 1;
                    n--;
                }
            }
            if (n <= 0) return true;
        }
        return false;
    }
};

int main() {
    Solution so;
    vector<int> nums = {1, 0, 0, 0, 1, 0};
    cout << so.canPlaceFlowers(nums, 2);
    return 0;
}
